package com.example.admin.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.SysDeptRole;
import com.example.admin.SysPermission;
import com.example.admin.SysRole;
import com.example.admin.SysUser;
import com.example.admin.entity.SysRoleVo;
import com.example.admin.service.ISysRoleService;
import com.example.shrio.CurrentUser;
import com.example.admin.service.impl.DataScope;
import com.example.util.APIState;
import com.example.util.AjaxResult;
import com.example.util.page.Pager;
import com.example.util.page.SeachParamsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色信息表 前端控制器
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@RestController
@Api(value = "系统角色Controller", tags = {"系统角色操作接口"})
@RequestMapping("/sys/sysRole")
public class SysRoleController {

    @Autowired
    private ISysRoleService service;

    @Autowired
    private DataScope dataScope;

    /**
     * 获取角色
     *
     * @param pager
     * @return
     */
    @ApiOperation(value = "系统角色列表", httpMethod = "POST")
    @PostMapping(value = "/page")
    public AjaxResult page(@RequestBody Pager pager) {
        Page<SysRole> page = new Page<>();
        page.setCurrent(pager.getPageNum());
        page.setSize(pager.getPageSize());
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        SeachParamsUtil.loadSearchParam(pager, queryWrapper);
        queryWrapper.ne("code", "admin");
        dataScope.dataScope(queryWrapper);
        pager.convertPage(service.page(page, queryWrapper));
        return new AjaxResult(APIState.S00, pager);
    }

    /**
     * 保存
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "系统角色新增", httpMethod = "POST")
//    @Log(title = "角色信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult save(@RequestBody SysRoleVo vo) {
        SysRole sysRole = vo;
        if (vo.getPerms() != null && vo.getPerms().length > 0) {
            sysRole.setPermissions(Arrays.asList(vo.getPerms()).stream().map(x -> {
                        SysPermission permission = new SysPermission();
                        permission.setId(x);
                        return permission;
                    }
            ).collect(Collectors.toList()));
        }
        if (sysRole != null) {
            sysRole.setCreateTime(new Date());
            sysRole.setCreateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            if (service.saveRole(sysRole)) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 修改
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "系统角色修改", httpMethod = "PUT")
//    @Log(title = "角色信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult update(@RequestBody SysRoleVo vo) {
        SysRole sysRole = vo;
        if (vo.getPerms() != null && vo.getPerms().length > 0) {
            sysRole.setPermissions(Arrays.asList(vo.getPerms()).stream().map(x -> {
                        SysPermission permission = new SysPermission();
                        permission.setId(x);
                        return permission;
                    }
            ).collect(Collectors.toList()));
        }
        if (sysRole != null) {
            sysRole.setUpdateTime(new Date());
            sysRole.setUpdateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            if (service.updateRole(sysRole)) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    //数据权限
    @ApiOperation(value = "角色数据权限", httpMethod = "PUT")
//    @Log(title = "角色数据权限", businessType = BusinessType.UPDATE)
    @PutMapping("dataScope")
    public AjaxResult updateDataScope(@RequestBody SysRoleVo vo) {
        SysRole sysRole = vo;
        if (vo.getPerms() != null && vo.getPerms().length > 0) {
            sysRole.setDeptRoles(Arrays.asList(vo.getPerms()).stream().map(x -> {
                        SysDeptRole deptRole = new SysDeptRole();
                        deptRole.setDeptId(x);
                        deptRole.setRoleId(sysRole.getId());
                        return deptRole;
                    }
            ).collect(Collectors.toList()));
        }
        if (sysRole != null) {
            sysRole.setUpdateTime(new Date());
            sysRole.setUpdateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            if (service.updateRole(sysRole)) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "角色删除", httpMethod = "DELETE")
//    @Log(title = "角色信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult delete(@PathVariable Integer[] ids) {
        if (service.deleteRole(Arrays.asList(ids))) {
            return new AjaxResult(APIState.S00, "保存成功");
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }


    @ApiOperation(value = "角色启用/停用", httpMethod = "PUT")
//    @Log(title = "角色启用/停用", businessType = BusinessType.UPDATE)
    @PutMapping("start")
    public AjaxResult start(Integer id) {
        SysRole sysRole = service.getById(id);
        if (sysRole != null) {
            if (sysRole.getStart() == 1) {
                sysRole.setStart(0);
            } else {
                sysRole.setStart(1);
            }
            sysRole.setUpdateTime(new Date());
            sysRole.setUpdateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            if (service.updateById(sysRole)) {
                return new AjaxResult(APIState.S00, "更改成功");
            }
        }
        return new AjaxResult(APIState.S01, "更改失败");
    }

    /**
     * 获取角色信息
     *
     * @return
     */
    @ApiOperation(value = "获取角色信息", httpMethod = "GET")
    @GetMapping(value = "/list/role")
    public List<SysRole> getList() {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<SysRole>();
        queryWrapper.ne("code", "admin");
        return service.list(queryWrapper);
    }

    @ApiOperation(value = "获取用户角色信息", httpMethod = "GET")
    @GetMapping(value = "/{act}/{userId}")
    public AjaxResult getUserList(@PathVariable String act, @PathVariable Integer userId) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<SysRole>();
        queryWrapper.ne("code", "admin");
        dataScope.dataScope(queryWrapper);
        List<SysRole> roles = service.list(queryWrapper);
        SysUser sysUser = CurrentUser.getAdminUser();
        if (!sysUser.getAccount().equals("admin")) {
            roles.addAll(sysUser.getRoleList());
        }
        JSONObject result = new JSONObject();
        result.put("roles", roles);
        result.put("users", null);
        if (act.equals("edit")) {
            List<SysRole> users = service.getRoleList(userId);
            result.put("users", users.stream().map(info -> info.getId()).collect(Collectors.toList()));
        }
        return new AjaxResult(APIState.S00, result);
    }

}
